//
//  HMDownloadIMGOperation.m
//  自定义Operation
//
//  Created by teacher on 16/10/11.
//  Copyright © 2016年 itcast. All rights reserved.
//

#import "HMDownloadIMGOperation.h"
#import "CZAdditions.h"


@implementation HMDownloadIMGOperation

+(instancetype)operationWithURLString:(NSString *)urlString complete:(void (^)(UIImage *))completeBlock{
    HMDownloadIMGOperation *op = [[self alloc] init];
    
    op.urlString = urlString;
    op.completeBlock = completeBlock;
    
    return op;
}

/*
 The default implementation of this method does nothing. You should override this method to perform the desired task. In your implementation, do not invoke super. This method will automatically execute within an autorelease pool provided by NSOperation, so you do not need to create your own autorelease pool block in your implementation.
 默认没有实现,你因该重写此方法来执行你自己的任务.在你的实现中,不要super,会自动的有一个自动释放池,所以没有必要自己建
 */
- (void)main {
    //子线程运行
    
    //使用断言来确保block存在
    /*
     判断条件
     如果条件不满足 报错 打印出desc
     */
    NSAssert(self.completeBlock != nil, @"是给你看 block必须存在");
    
    NSURL *url = [NSURL URLWithString:self.urlString];
    
    [NSThread sleepForTimeInterval:2];
    NSData *data = [NSData dataWithContentsOfURL:url];
    
    [data writeToFile:[self getPathWithUrlString:_urlString] atomically:YES];
    
    if ([self isCancelled]) {
        NSLog(@"取消");
        return;
    }
    UIImage *image = [UIImage imageWithData:data];
    
    //问题:把下载完的图片交还给调用方
    //会到主线程,因为大多数情况下,调用方式拿到图片直接显示到界面,需要在主线程执行,我们写的是一个通用的图片下载任务,需要怎么好用怎么来,在操作内部把线程间通信已经完成了
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{

        self.completeBlock(image);
        
    }];
    
}

- (NSString *) getPathWithUrlString:(NSString *)urlString {

    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    
    NSString *fileName = [urlString cz_md5String];
    
    return [cachePath stringByAppendingPathComponent:fileName];
}
@end
